<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        #box{
            width: 100px;
            height: 100px;
            border: 1px solid #000;
            background-color: #abcdef;
            position: absolute;
            left:100px;
            top: 100px;
            cursor: pointer;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <h1>JS 图层拖拽</h1>
    <hr>

    <div id="box"></div>

    <script>
    // 按下
    box.onmousedown = function (env) {
        this.style.backgroundColor = '#f90';
        this.innerHTML = '按下';


        var env = env || window.event;
        // 按下时.计算出 鼠标在box上的相对位置
        var left = env.clientX - box.offsetLeft;
        var top = env.clientY - box.offsetTop;
        console.log(left, top);

        // 移动
        document.onmousemove = function (en) {
            var en = en || window.event;
            // 获取鼠标位置
            var x = en.clientX - left;
            var y = en.clientY - top;

            // 给box重新定位
            box.style.left = x + 'px';
            box.style.top = y + 'px';
        }
    }

    // 松开
    document.onmouseup = function () {
        box.style.backgroundColor = '#abcdef';
        box.innerHTML = '松开';
        // 解绑移动事件
        document.onmousemove = null;
    }


    </script>
</html>
</body>